﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Website.Data;

namespace Website
{
    public partial class KmlMap : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["daddr"] != null &&
                Request.QueryString["key"] != null &&
                Request.QueryString["type"] != null &&
                Request.QueryString["modeType"] != null)
            {
                string address = Request.QueryString["daddr"];
                string[] position = address.Split(',');
                float latitude = Convert.ToSingle(position[0]);
                float longitude = Convert.ToSingle(position[1]);
                int key = Convert.ToInt32(Request.QueryString["key"]);
                string type = Request.QueryString["type"];
                string modeType = Request.QueryString["modeType"];

                StringBuilder kmlContent = type == "Custom" ? new StringBuilder(GetCustomKmlMap(latitude, longitude, key, type, modeType)) : new StringBuilder(GetKmlMap(latitude, longitude, key, type, modeType));

                Response.Clear();
                Response.ContentType = "text/xml; charset=utf-8";
                Response.Write(kmlContent);

                Response.End();
            }
        }

        private static string GetCustomKmlMap(float latitude, float longitude, int key, string type, string modeType)
        {
            var kmlContent = string.Empty;

            using (System.Data.SqlClient.SqlConnection _SqlConnection = DataAccess.SqlConnection(modeType))
            {
                var _SqlCommand = new SqlCommand(GetSPNameByType(type), _SqlConnection);

                _SqlCommand.CommandType = CommandType.StoredProcedure;
                _SqlCommand.Parameters.AddWithValue("@latitude", latitude);
                _SqlCommand.Parameters.AddWithValue("@longitude", longitude);
                _SqlCommand.Parameters.AddWithValue("@key", key);

                //Gets closest Ids
                using (var reader = _SqlCommand.ExecuteReader())
                {
                    string distributionIdList = string.Empty;
                    string xMissionIdList = string.Empty;

                    if (reader != null)
                        while (reader.Read())
                        {
                            if (reader["WorkQueueType"] != DBNull.Value && (string) reader["WorkQueueType"] == "XMission")
                                xMissionIdList = reader["Ids"] as string;

                            if (reader["WorkQueueType"] != DBNull.Value && (string) reader["WorkQueueType"] == "Distribution")
                                distributionIdList = reader["Ids"] as string;
                       }

                    if (reader != null) reader.Close();

                    kmlContent = GetKmlContent(_SqlConnection, null, null, null, null, null, null, xMissionIdList,
                                               "Key", null, null, distributionIdList, "Key");

                }
            }

            return kmlContent;
        }

        private static string GetKmlMap(float latitude, float longitude, int key, string type, string modeType)
        {
            var kmlContent = string.Empty;

            using (System.Data.SqlClient.SqlConnection _SqlConnection = DataAccess.SqlConnection(modeType))
            {
                var _SqlCommand = new SqlCommand(GetSPNameByType(type), _SqlConnection);

                _SqlCommand.CommandType = CommandType.StoredProcedure;
                _SqlCommand.Parameters.AddWithValue("@latitude", latitude);
                _SqlCommand.Parameters.AddWithValue("@longitude", longitude);
                _SqlCommand.Parameters.AddWithValue("@key", key);

                //Gets closest Ids
                using (var reader = _SqlCommand.ExecuteReader()) 
                {
                    if (reader != null && reader.Read())
                    {
                        var ids = reader[0] as string;
                        reader.Close();

                        if (ids != null)
                        {
                            switch (type)
                            {
                                case "AssetsDistribution":
                                    kmlContent = GetKmlContent(_SqlConnection, null, null, ids, "Key", null, null, null,
                                                               null, null, null, null, null);
                                    break;
                                case "AssetsXmission":
                                    kmlContent = GetKmlContent(_SqlConnection, ids, "Key", null, null, null, null, null,
                                                               null, null, null, null, null);
                                    break;
                                case "ProjectsDistributionInspection":
                                    kmlContent = GetKmlContent(_SqlConnection, null, null, null, null, null, null, null,
                                                               null, null, null, ids, "Key");
                                    break;
                                case "ProjectsXmissionInspection":
                                    kmlContent = GetKmlContent(_SqlConnection, null, null, null, null, null, null, ids,
                                                               "Key", null, null, null, null);
                                    break;
                                case "ProjectsDistributionGpsVisit":
                                    kmlContent = GetKmlContent(_SqlConnection, null, null, null, null, null, null, null,
                                                               null, null, ids, "Key", null);
                                    break;
                                case "ProjectsXmissionGpsVisit":
                                    kmlContent = GetKmlContent(_SqlConnection, null, null, null, null, ids, "Key", null,
                                                               null, null, null, null, null);
                                    break;
                            }
                        }
                    }
                }
            }

            return kmlContent;
        }

        private static string GetSPNameByType(string type)
        {
            string spName = string.Empty;

            switch (type)
            {
                case "AssetsDistribution":
                    spName = "up_MapHtml_AssetDistributionPoleSelectClosest";
                    break;
                case "AssetsXmission":
                    spName = "up_MapHtml_AssetXmissionStructureSelectClosest";
                    break;
                case "ProjectsDistributionInspection":
                    spName = "up_MapHtml_InspVisitDistributionPoleSelectClosest";
                    break;
                case "ProjectsXmissionInspection":
                    spName = "up_MapHtml_InspVisitXmissionStructureSelectClosest";
                    break;
                case "ProjectsDistributionGpsVisit":
                    spName = "up_MapHtml_GpsVisitDistributionPoleSelectClosest";
                    break;
                case "ProjectsXmissionGpsVisit":
                    spName = "up_MapHtml_GpsVisitXmissionStructureSelectClosest";
                    break;
                case "Custom":
                    spName = "up_MapHtml_InspVisitWorkQueue";
                    break;
            }

            return spName;
        }
        
        private static string GetKmlContent(SqlConnection _SqlConnection,
            string transmissionStructuresList, string transmissionStructuresText,
            string distributionPolesList, string distributionPolesText,
            string transmissionGpsVisitsList, string transmissionGpsVisitsText,
            string transmissionInspectionVisitsList, string transmissionInspectionVisitsText,
            string distributionGpsVisitsList, string distributionGpsVisitsText,
            string distributionInspectionVisitsList, string distributionInspectionVisitsText)

        {
            var _SqlCommand = new SqlCommand("up_KML", _SqlConnection);
            _SqlCommand.CommandType = CommandType.StoredProcedure;

            // add parameters (always translate empty strings to nulls)
            _SqlCommand.Parameters.AddWithValue("@TranmissionStructuresList", string.IsNullOrEmpty(transmissionStructuresList) ? null : transmissionStructuresList);
            _SqlCommand.Parameters.AddWithValue("@TranmissionStructuresText", string.IsNullOrEmpty(transmissionStructuresText) ? "Key" : transmissionStructuresText);
            _SqlCommand.Parameters.AddWithValue("@DistributionPolesList", string.IsNullOrEmpty(distributionPolesList) ? null : distributionPolesList);
            _SqlCommand.Parameters.AddWithValue("@DistributionPolesText", string.IsNullOrEmpty(distributionPolesText) ? "Key" : distributionPolesText);
            _SqlCommand.Parameters.AddWithValue("@TransmissionGpsVisitsList", string.IsNullOrEmpty(transmissionGpsVisitsList) ? null : transmissionGpsVisitsList);
            _SqlCommand.Parameters.AddWithValue("@TransmissionGpsVisitsText", string.IsNullOrEmpty(transmissionGpsVisitsText) ? "Key" : transmissionGpsVisitsText);
            _SqlCommand.Parameters.AddWithValue("@TransmissionInspectionVisitsList", string.IsNullOrEmpty(transmissionInspectionVisitsList) ? null : transmissionInspectionVisitsList);
            _SqlCommand.Parameters.AddWithValue("@TransmissionInspectionVisitsText", string.IsNullOrEmpty(transmissionInspectionVisitsText) ? "Key" : transmissionInspectionVisitsText);
            _SqlCommand.Parameters.AddWithValue("@DistributionGpsVisitsList", string.IsNullOrEmpty(distributionGpsVisitsList) ? null : distributionGpsVisitsList);
            _SqlCommand.Parameters.AddWithValue("@DistributionGpsVisitsText", string.IsNullOrEmpty(distributionGpsVisitsText) ? "Key" : distributionGpsVisitsText);
            _SqlCommand.Parameters.AddWithValue("@DistributionInspectionVisitsList", string.IsNullOrEmpty(distributionInspectionVisitsList) ? null : distributionInspectionVisitsList);
            _SqlCommand.Parameters.AddWithValue("@DistributionInspectionVisitsText", string.IsNullOrEmpty(distributionInspectionVisitsText) ? "Key" : distributionInspectionVisitsText);

            string kmlContent = string.Empty;

            using (var xmlReader = _SqlCommand.ExecuteReader())
            {
                if (xmlReader.Read())
                    kmlContent = xmlReader[0] as string;

                xmlReader.Close();
            }

            return kmlContent;
        }
    }
}
